package ldh.im.fxbase.dao;

import ldh.rpc.dto.ValueEnum;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;

public class BaseDao {

    protected static final Logger LOGGER = LoggerFactory.getLogger(BaseDao.class);

//    public <T> T getBeanById(QueryRunner queryRunner, Connection connection, Class<T> beanClass, String tableName, Number id) throws SQLException {
//        String sql = String.format("select * from %s where id = ?", tableName);
//        T t = queryRunner.query(connection, sql, new BeanHandler<>(beanClass), id);
//        return t;
//    }

    public void updateBeanById(QueryRunner queryRunner, Connection connection, String sql, Object...params) throws SQLException {
        int n = queryRunner.execute(connection, sql, params);
        if (n != 1) {
            throw new RuntimeException("更新数据失败!!");
        }
    }

    public Byte valueEnum(Enum enumValue) {
        if (enumValue == null) return null;
        if (enumValue instanceof ValueEnum) {
            return (byte) ((ValueEnum) enumValue).getValue();
        }
        throw new RuntimeException(enumValue + "不支持取值");
    }

    protected int[] batchUpdates(QueryRunner queryRunner, Connection connection, String sql, Object[][] params) throws SQLException {
        int[] ns = queryRunner.batch(connection, sql, params);
        if (ns.length != params.length) {
            throw new RuntimeException("更新im_message失败， n =" + ns.length);
        }
        return ns;
    }
}
